package com.jf.cloud.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.api.multishop.feign.ShopSubstituteSalesFeignClient;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.constant.DistributedIdKey;
import com.jf.cloud.common.constant.StatusEnum;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.product.constant.*;
import com.jf.cloud.common.product.dto.SkuDTO;
import com.jf.cloud.common.product.dto.SpuAttrValueDTO;
import com.jf.cloud.common.product.dto.SpuDTO;
import com.jf.cloud.common.product.dto.SpuLangDTO;
import com.jf.cloud.common.product.vo.SkuVO;
import com.jf.cloud.common.product.vo.SpuAttrValueVO;
import com.jf.cloud.common.product.vo.SpuDetailVO;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.PriceUtil;
import com.jf.cloud.common.vo.ShopSubstituteSalesVO;
import com.jf.cloud.common.product.constant.SpuStatus;
import com.jf.cloud.product.mapper.BrandMapper;
import com.jf.cloud.product.mapper.SkuMapper;
import com.jf.cloud.product.mapper.SpuMapper;
import com.jf.cloud.product.model.*;
import com.jf.cloud.product.service.*;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zz
 * @date 2022/8/2 14:09
 */
@Lazy
@Service
public class ImportSupplierSpuServiceImpl implements ImportSupplierSpuService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private ShopSubstituteSalesFeignClient shopSubstituteSalesFeignClient;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SpuExtensionService spuExtensionService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SpuLangService spuLangService;
    @Autowired
    private SpuDetailService spuDetailService;
    @Autowired
    private SpuConsignmentChangeService spuConsignmentChangeService;
    @Autowired
    private SegmentFeignClient segmentFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSpu(Long supplierSpuId, Long shopId, Integer sysType, Long userId, Boolean isPurchaseOrder) {
        Long spuId = supplierSpuId;
        if (Objects.isNull(spuId)){
            shopId = AuthUserContext.get().getTenantId();
        }
        //查看是否已导入
        SpuVO commissionSup = spuMapper.getSpuByShopIdAndSupplierSpuId(shopId, supplierSpuId);
        if (!Objects.isNull(commissionSup)){
            return;
        }
        //查找供应商spu信息
        SpuVO spuVo = spuMapper.getBySpuId(spuId);
        SpuDTO spuDTO = mapperFacade.map(spuVo, SpuDTO.class);
        //商品状态默认为下架
        spuDTO.setStatus(SpuStatus.OFF_SHELF.value());
        //供应商商品类型：商家代销
        spuDTO.setSupplierSpuType(SupplierSpuType.CONSIGNMENT.value());
        //发货方式：供应商发货
        if (Objects.equals(spuVo.getStatus(), StatusEnum.DISABLE.value())){
            spuDTO.setSupplierDeliveryType(SupplierDeliveryType.SHOP_DELIVERY.value());
        }else {
            spuDTO.setSupplierDeliveryType(SupplierDeliveryType.SUPPLIER_DELIVERY.value());
        }
        // 如果是采购订单时导入商品发货方式需要变成商家发货
        if (isPurchaseOrder){
            spuDTO.setSupplierDeliveryType(SupplierDeliveryType.SHOP_DELIVERY.value());
        }
        //关联商品商品id
        spuDTO.setSupplierSpuId(spuVo.getSpuId());
        //代销商品规格选择状态:全选
        spuDTO.setSkuChoiceStatus(SkuChoiceStatus.ALL_CHOICE.value());
        //供应商id
        spuDTO.setSupplierId(spuVo.getSupplierId());
        spuDTO.setShopId(shopId);
        //代销商品无需模板id
        spuDTO.setDeliveryTemplateId(null);
        //获取商家代销设置
        ServerResponseEntity<ShopSubstituteSalesVO> salesType = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId);
        ShopSubstituteSalesVO shopSubstituteSalesVO = salesType.getData();
        if (Objects.isNull(shopSubstituteSalesVO)){
            // 保存店铺代销设置默认值
            shopSubstituteSalesFeignClient.saveDefault(shopId);
            shopSubstituteSalesVO = shopSubstituteSalesFeignClient.getByShopSubstituteSalesId(shopId).getData();
        }
        spuDTO.setPriceFee(computeSpuPrice(spuDTO, shopSubstituteSalesVO));
        spuDTO.setMarketPriceFee(spuDTO.getMarketPriceFee());
        spuDTO.setScoreFee(Objects.isNull(spuDTO.getScoreFee()) ? Constant.ZERO_LONG : spuDTO.getScoreFee());
        //保存商品信息
        Spu spu = mapperFacade.map(spuDTO, Spu.class);
        ServerResponseEntity<Long> segmentIdResponse = segmentFeignClient.getSegmentId(DistributedIdKey.MALL4CLOUD_SPU);
        if (!segmentIdResponse.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        spu.setSpuId(segmentIdResponse.getData());
        spu.setSkuZoned(0);
        spuMapper.save(spu);
        //保存 商家代销商品基本信息相对于供应商品是否改变
        SpuConsignmentChange spuConsignmentChange = new SpuConsignmentChange();
        spuConsignmentChange.setSpuId(spu.getSpuId());
        spuConsignmentChangeService.save(spuConsignmentChange);
        //查询供应商商品属性
        List<SpuAttrValueVO> spuAttrs = spuAttrValueService.getSpuAttrsBySpuId(supplierSpuId);
        List<SpuAttrValueDTO> spuAttrValueDTOS = new ArrayList<>();
        for (SpuAttrValueVO spuAttr : spuAttrs) {
            SpuAttrValueDTO spuAttrValueDTO = new SpuAttrValueDTO();
            spuAttr.setSpuId(spu.getSpuId());
            spuAttrValueDTO.setAttrId(spuAttr.getAttrId());
            spuAttrValueDTO.setAttrName(spuAttr.getSpuAttrValueLangList().get(0).getAttrName());
            spuAttrValueDTO.setAttrValueName(spuAttr.getSpuAttrValueLangList().get(0).getAttrValueName());
            if (!Objects.isNull(spuAttr.getAttrValueId())) {
                spuAttrValueDTO.setAttrValueId(spuAttr.getAttrValueId());
            }
            spuAttrValueDTOS.add(spuAttrValueDTO);
        }
        // 2.保存商品属性信息
        spuAttrValueService.save(spu.getSpuId(), spu.getCategoryId(), spuAttrValueDTOS, sysType);
        // 3.国际化信息、商品详情
        spuDTO.setSpuId(spu.getSpuId());
        loadSpuLangInfo(spuDTO, Boolean.TRUE);
        //保存商品扩展信息
        SpuExtension spuExtension = new SpuExtension();
        spuExtension.setSpuId(spu.getSpuId());
        spuExtension.setActualStock(0);
        spuExtension.setStock(0);
        spuExtension.setSaleNum(0);
        spuExtensionService.save(spuExtension);
        //sku信息
        List<SkuVO> skuVOS = skuMapper.listSkuWithAttrBySpuId(spuId);
        List<SkuDTO> skuDTOs = new ArrayList<>();
        for (SkuVO skuVO : skuVOS) {
            skuVO.setPriceFee(computeSkuPrice(skuVO, shopSubstituteSalesVO));
            skuVO.setMarketPriceFee(skuVO.getMarketPriceFee());
            SkuDTO skuDTO = mapperFacade.map(skuVO, SkuDTO.class);
            skuDTO.setSupplierSkuId(skuDTO.getSkuId());
            skuDTO.setSpuId(null);
            skuDTO.setStock(0);
            skuDTOs.add(skuDTO);
        }
        //保存sku信息
        skuService.save(spu.getSpuId(), skuDTOs, sysType, userId, shopId);
        // 更新品牌信息
        brandMapper.batchUpdateSpuCount(Collections.singleton(spu.getBrandId()));
    }

    private void loadSpuLangInfo(SpuDTO spuDTO, Boolean isSave) {
        List<SpuDetail> spuDetailList = new ArrayList<>();
        List<SpuLang> spuLangList = new ArrayList<>();
        boolean dataCorrect = false;
        for (SpuLangDTO spuLangDTO : spuDTO.getSpuLangList()) {
            SpuLang spuLang = mapperFacade.map(spuLangDTO, SpuLang.class);
            spuLang.setSpuId(spuDTO.getSpuId());
            boolean isBlank = StrUtil.isBlank(spuLang.getSpuName()) && StrUtil.isBlank(spuLang.getSellingPoint());
            if (!isBlank) {
                spuLangList.add(spuLang);
            }
            List<SpuDetailVO> detailList = spuDTO.getDetailList();
            if(CollUtil.isNotEmpty(detailList)){
                spuDetailList = detailList.stream().map(spuDetailVO -> {
                    SpuDetail detail = new SpuDetail();
                    detail.setSpuId(spuDTO.getSpuId());
                    detail.setDetail(spuDetailVO.getDetail());
                    detail.setLang(spuDetailVO.getLang());
                    return detail;
                }).collect(Collectors.toList());
            }else{
                if (StrUtil.isNotBlank(spuLangDTO.getDetail())) {
                    SpuDetail spuDetail = new SpuDetail();
                    spuDetail.setSpuId(spuDTO.getSpuId());
                    spuDetail.setLang(spuLangDTO.getLang());
                    spuDetail.setDetail(spuLangDTO.getDetail());
                    spuDetailList.add(spuDetail);
                }
            }
            if (!isBlank && Objects.equals(spuLang.getLang(), Constant.DEFAULT_LANG)) {
                dataCorrect = true;
            }

        }

        // 商品名称、卖点，商品详情，是否包含默认语言信息
        if (CollUtil.isEmpty(spuLangList) || !dataCorrect) {
            throw new LuckException(ResponseEnum.DATA_ERROR);
        }
        if (isSave) {
            if (spuDetailList.size() != 0) {
                spuDetailService.batchSave(spuDetailList);
            }
            if (spuLangList.size() != 0) {
                spuLangService.batchSave(spuLangList);
            }
            return;
        }
        SpuVO spuDb = spuMapper.getBySpuId(spuDTO.getSpuId());
        spuDetailService.update(spuDetailList, spuDb.getDetailList(), spuDb.getSpuId());
        spuLangService.update(spuLangList, spuDb.getSpuId());
    }

    /**
     * 根据代销设置计算代销商品Spu售价
     * @param spuDTO
     * @param shopSubstituteSalesVO
     * @return
     */
    private Long computeSpuPrice(SpuDTO spuDTO,ShopSubstituteSalesVO shopSubstituteSalesVO){
        Long spuPriceFee = 0L;

        if (Objects.equals(shopSubstituteSalesVO.getSalesType() , SalesType.SMART_PRICE.value())) {
            //智能设价计算售价
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.PROPORTION_PRICE.value())) {
                //按比例加价
                spuPriceFee = PriceUtil.divideByBankerRounding(spuDTO.getPriceFee() * shopSubstituteSalesVO.getSalesPrice(), 10000) + spuDTO.getPriceFee();
            }
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.FIXED_NUMBER_PRICE.value())) {
                    //按固定数值加价
                    spuPriceFee = spuDTO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
            }
        }
        if (Objects.equals(shopSubstituteSalesVO.getSalesType() , SalesType.MANUAL_OPERATION_PRICE.value())){
            //手动设价
            spuPriceFee = spuDTO.getPriceFee();
        }
        return spuPriceFee;
    }

    /**
     * 根据代销设置计算代销商品sku售价
     * @param skuVO
     * @param shopSubstituteSalesVO
     * @return
     */
    private Long computeSkuPrice(SkuVO skuVO,ShopSubstituteSalesVO shopSubstituteSalesVO){
        Long skuPriceFee = 0L;
        if (Objects.equals(shopSubstituteSalesVO.getSalesType() , SalesType.SMART_PRICE.value())) {
            //智能设价计算售价
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.PROPORTION_PRICE.value())) {
                //按比例加价
                skuPriceFee = priceRound(skuVO,shopSubstituteSalesVO);
            }
            if (Objects.equals(shopSubstituteSalesVO.getSalesPriceType(), SalesPriceType.FIXED_NUMBER_PRICE.value())) {
                //按固定数值加价
                skuPriceFee = skuVO.getPriceFee() + shopSubstituteSalesVO.getSalesPrice();
            }
        }

        if (Objects.equals(shopSubstituteSalesVO.getSalesType() , SalesType.MANUAL_OPERATION_PRICE.value())){
            //手动设价
            skuPriceFee = skuVO.getPriceFee();
        }
        return skuPriceFee;
    }

    private Long priceRound(SkuVO skuVO,ShopSubstituteSalesVO shopSubstituteSalesVO){
        Long priceFee = skuVO.getPriceFee();
        double priceFeeD = Double.parseDouble(priceFee.toString());
        Long salesPrice = shopSubstituteSalesVO.getSalesPrice();
        double salesPriceD = Double.parseDouble(salesPrice.toString());
        Double addPrice = (priceFeeD * salesPriceD) / 10000;

        BigDecimal bigDecimal= new BigDecimal(addPrice);
        addPrice = bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();

        return new Double(priceFee + addPrice).longValue();
    }

}
